<template>
  <div class="page-container warehouse-container">
    <el-tabs v-model="activeName">
      <el-tab-pane label="用户产线及仓库配置" name="1"></el-tab-pane>
      <el-tab-pane label="我的CAD任务" name="2"></el-tab-pane>
    </el-tabs>
    <div v-if="activeName == 1">
      <div style="padding:10px;">
        <el-page-header @back="$router.back()" content="用户产线及仓库配置"></el-page-header>
      </div>
      <h4 style="padding-left:30px;">当前团队：{{userInfo && userInfo.company && userInfo.company.name}}</h4>
      <h4 style="padding-left:30px;">{{userInfo && userInfo.name}}账号:{{userInfo && userInfo.phone}}</h4>
      <el-form ref="form" label-width="100px" :model="form" :rules="rules">
        <el-form-item label="公司(组织)" prop="companyId">
          <el-select v-model="form.companyId" placeholder="请选择" @change="companyChange">
            <el-option v-for="item in allCompany" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工厂/产线" prop="userOrgs">
          <el-cascader style="width:500px" popper-class="warehouse-cascader" v-model="form.userOrgs" :options="allOrgData" :props="{label:'name',multiple: true,value:'id',checkStrictly:true}" @change="cascaderChange"></el-cascader>
          <el-button type="danger" style="margin-left:10px;" @click="handleUserCommand(2)">清空</el-button>
        </el-form-item>
        <el-form-item label="仓库" prop="companyId">
          <el-cascader style="width:500px" popper-class="warehouse-cascader" v-model="form.userWarehouses" :options="allWarehouse" :props="{label:'name',multiple: true,value:'id',checkStrictly:true}"></el-cascader>
          <el-button type="danger" style="margin-left:10px;" @click="handleUserCommand(3)">清空</el-button>
        </el-form-item>
        <el-form-item label="机床">
          <el-button type="primary">绑定产线机床</el-button>
          <el-alert style="display:inline;margin-left:20px;" title="您有尚未绑定的机床的产线" type="warning" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleUserCommand(1)">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="activeName == 2">
      <div style="padding:10px;">
        <el-page-header @back="$router.back()" content="我的CAD任务"></el-page-header>
      </div>
      <el-collapse v-model="collapseActive" :accordion="false">
        <el-collapse-item title="上传零件任务" name="1">
          <el-alert v-if="uploadPartInfo" title="上传零件任务" :closable="false" type="success" :description="`当前您有一个ID为${uploadPartInfo}的零件任务正在处理中`">
          </el-alert>
          <div class="result-button" v-if="uploadPartInfo">
            <el-button type="danger" @click="clearStore(1)">清除任务</el-button>
          </div>
          <el-empty v-else :image-size="50"></el-empty> 
        </el-collapse-item>
        <el-collapse-item title="排样任务" name="2">
          <el-alert v-if="uploadLayoutInfo" title="零件排样任务" :closable="false" type="warning" :description="`当前您有一个ID为${nameLayout}的排样任务正在处理中`">
          </el-alert>
          <div class="result-button" v-if="uploadLayoutInfo">
            <el-button type="danger" @click="clearStore(2)">清除任务</el-button>
          </div>
          <el-empty v-else :image-size="50"></el-empty>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
import { v4 as uuidv4 } from 'uuid';
import { mapState } from 'vuex';
import { clone, findIndex, uniqBy, find, uniq } from 'lodash';
export default {
  name: 'admin',
  data() {
    return {
      activeName: '1',
      collapseActive: ['1', '2'],
      allCompany: [],
      allOrgData: [],
      allWarehouse: [],
      lastLevelOptions: [],
      form: {
        companyId: '',
        userOrgs: [],
        userWarehouses: [],
      },
      rules: {
        companyId: [
          { required: true, message: "公司(组织)不能为空", trigger: "change" },
        ],
        userOrgs: [
          { required: true, message: "工厂/产线不能为空", trigger: "change" },
        ],
        userWarehouses: [
          { required: true, message: "仓库不能为空", trigger: "change" },
        ]
      }
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.app.userInfo,
      uploadPartInfo: (state) => state.resource.uploadPartInfo,
      uploadLayoutInfo:(state) =>state.resource.uploadLayoutInfo
    }),
    nameLayout:function(){
      if(this.uploadLayoutInfo && Array.isArray(this.uploadLayoutInfo.Parts)){
        let names=[];
        this.uploadLayoutInfo.Parts.forEach(item=>{
          names.push(item.partId)
        }) 
        return names.join(',');
      }
      return ''
    }
  },
  mounted() {
    this.getOrgList();
  },
  methods: {
    handleAddUserCommand() {
      if (this.checkedAllWarehouse.length == 0) return this.$message.error('请选择仓库');
      let treeUserOrgData = clone(this.treeUserOrgData);
      let treeUserWarehouse = clone(this.treeUserWarehouse);
      this.treeAllWarehouse.forEach(item => {
        if (item.warehouse && Array.isArray(item.warehouse)) {
          let isAdd = false;
          item.warehouse.forEach(val => {
            let cIndex = findIndex(this.checkedAllWarehouse, o => o === val.id);
            if (cIndex >= 0) {
              isAdd = true;
              treeUserWarehouse.push({ name: val.name, id: val.id, orgId: val.orgId, orgName: val.orgName })
            }
          })
          if (isAdd) {
            treeUserOrgData.push({ name: item.name, id: item.id })
          }
        }

      })
      this.treeUserWarehouse = uniqBy(treeUserWarehouse, o => o.id);
      this.treeUserOrgData = uniqBy(treeUserOrgData, o => o.id);
    },
    handleUserCommand(flag, rows) {
      let title = '';
      if (flag === 1) {
        title = "确定将已勾选仓库添加到我的仓库中？";
      } else if (flag === 2) {
        title = "确定移除组织及组织下面的所有仓库？";
      } else if (flag === 3) {
        title = "确定移除所选仓库？";
      }
      this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (flag === 1) {
          console.log('this.form.userOrgs',this.form.userOrgs);
          console.log('this.form.userWarehouses',this.form.userWarehouses);
          this.$refs["form"].validate((valid) => {
            if (valid) {
              const loading = this.$loading({ text: '加载中...' });
              let userOrgs = this.form.userOrgs.map(item => item[item.length - 1]);
              let userWarehouses = this.form.userWarehouses.map(item => item[item.length - 1]);
              this.$http.post(this.$API.SET_USER_ORG + '?id=' + this.userInfo.id, userOrgs).then((res) => {
                this.$http.post(this.$API.SET_USER_WARES + '?id=' + this.userInfo.id, userWarehouses).then((res) => {
                  this.$message.success('操作成功');
                  loading.close();
                }).catch(err => {
                  loading.close();
                });
              }).catch(err => {
                loading.close();
              });
            }
          });
        } else if (flag === 2) {
          this.form.userOrgs = [];
          this.form.userWarehouses = [];
          this.allWarehouse = [];
        } else if (flag === 3) {
          this.form.userWarehouses = [];
          this.allWarehouse = [];
        }
      });
    },
    //获取全部组织架构
    getOrgList() {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .get(this.$API.ORGANIZATION, { companyId: this.userInfo.company.id })
        .then(res => {
          loading.close();
          let list = Array.isArray(res.data) ? res.data : [];
          // const getTreeData = (data) => {
          //   for (let i = 0; i < data.length; i++) {
          //     if (data[i].children.length < 1) {
          //       data[i].children = null;
          //     } else {
          //       getTreeData(data[i].children);
          //     }
          //   }
          // }
          // getTreeData(list);
          this.allOrgData = list;
          this.getUserOrg();
        })
        .catch(err => {
          loading.close();
        });
    },
    companyChange() {
      this.form.userOrgs = [];
      this.form.userWarehouses = [];
      this.allWarehouse = [];
    },
    cascaderChange(e) {
      this.allWarehouse = [];
      this.warehouseAjaxMethod();
    },
    getUserOrg() {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .get(this.$API.GET_USER_WARE, { userId: this.userInfo.id })
        .then(res => {
          loading.close();
          let list = Array.isArray(res.data) ? res.data : [], treeUserWarehouse = [], treeUserOrgData = [];
          this.allCompany = [this.userInfo.company];
          list.forEach(val => {
            treeUserWarehouse.push(val.id);
            if (val.organization) {
              treeUserOrgData.push(val.organization.id)
            }
          })
          this.form = {
            companyId: this.userInfo.company.id,
            userOrgs: uniq(treeUserOrgData).map(o=>[o]),
            userWarehouses: uniq(treeUserWarehouse).map(o=>[o]),
          }
          if (list.length === 0) return;
          this.warehouseAjaxMethod();
          this.$forceUpdate();
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //仓库
    warehouseAjaxMethod() {
      const loading = this.$loading({ text: '加载中...' });
      let keys = this.form.userOrgs.map(item => item[item.length - 1]);
      this.$http
        .get(this.$API.GET_WAREHOUSE + '?' + keys.map(o => 'orgIds=' + o).join('&'))
        .then(res => {
          loading.close();
          let warehouse = Array.isArray(res.data) ? res.data : [], userWarehouses = [];
          if (this.form.userWarehouses.length > 0) {
            this.form.userWarehouses.forEach(item => {
              let cIndex = findIndex(warehouse, o => o.id === item[0]);
              if (cIndex >= 0) userWarehouses.push(item)
            })
            this.form.userWarehouses = userWarehouses;
          }
          this.allWarehouse = warehouse;
        })
        .catch(err => {
          loading.close();
        });
    },
    // 回写数据的函数
    writeCascaderBack() {
      const fullPaths = [];
      // 遍历最后一级选项值
      this.lastLevelOptions.forEach(lastLevelValue => {
        // 调用 findPath 函数查找完整路径
        const path = this.findPath(this.allOrgData, lastLevelValue);
        if (path) {
          fullPaths.push(path);
        }
      });
      return fullPaths;
    },
    // 递归查找完整路径的函数
    findPath(options, targetValue, currentPath = []) {
      for (const option of options) {
        const newPath = [...currentPath, option.id];
        if (option.id === targetValue) {
          return newPath;
        }
        if (option.children) {
          const result = this.findPath(option.children, targetValue, newPath);
          if (result) {
            return result;
          }
        }
      }
      return null;
    },
    clearStore(flag){
      this.$confirm('此操作将删除任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        if(flag == 1){
          this.$store.dispatch('resource/setUploadPartInfo', null);
        }else if(flag == 2){
          this.$store.dispatch('resource/setUploadLayoutInfo', null);
        }
        this.$message.success('操作成功');
      });
    }
  }
};
</script>

<style lang="less">
.warehouse-container {
  padding: 10px;
  .all-warehouse-content {
    width: 45%;
    height: 100%;
    border: 1px solid #eee;
    border-radius: 6px;
    display: flex;

    .all-row {
      width: 50%;
      padding: 10px;
      height: 100%;

      .all-row-box {
        height: 100%;
        border: 1px solid #eee;
      }
    }
  }
  .result-button{
    padding:10px;
    display: flex;
    justify-content: flex-end;
  }

  .warehouse-center {
    width: 10%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .title {
    font-size: 14px;
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    span {
      font-weight: bold;
    }
  }

  .tree-group {
    height: 86vh;
  }
  .tree-user-group {
    height: 82vh;
    position: relative;
  }
  .tree-user-add {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 10px;
  }

  .user-warehouse-content {
    width: 45%;
    height: 100%;
    border: 1px solid #eee;
    border-radius: 6px;
    display: flex;

    .user-row {
      width: 50%;
      padding: 10px;
      height: 100%;

      .user-row-box {
        height: 100%;
        border: 1px solid #eee;
      }
    }
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .tree-checked {
    padding: 3px 20px;
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    color: #333;
  }
  .tree-org-name {
    font-size: 13px;
    padding: 5px 10px;
    margin: 0;
  }

  .tree-remove {
    font-size: 12px;
    color: red;
  }

  .add-remove {
    font-size: 12px;
    color: #66b1ff;
  }

  .title-user {
    font-weight: bold;
    justify-content: center;
  }
  .tree-checked-title {
    max-width: 85%;
  }
  .el-checkbox {
    display: flex;
    align-items: center;
  }
  .el-checkbox__label {
    max-width: 180px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.warehouse-cascader {
  top: 0 !important;
  left: 850px !important;
  bottom: 0 !important;
  .el-cascader-panel {
    height: 100%;
  }
  .el-cascader-menu__wrap {
    height: 100%;
  }
}
</style>